﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using STS.Schema.Interfaces;
using STS.Schema.Collections;
using STS.Schema.Base;
using STS.Interfaces;
using STS.Schema.Enums;

namespace STS.Schema.MSSql
{
    public class MSSqlForeignKey : SqlObjectBase, IForeignKey
    {
        private Lazy<ISqlObjectCollection> _foreignKeyColumnList;

        public override SqlObjectType ObjectType
        {
            get { return SqlObjectType.ForeignKey; }
        }

        [SqlQueryProperty("object_id")]
        public override int ObjectID { get; internal set; }

        [SqlQueryProperty("parent_object_id")]
        public override int? ParentObjectID{ get; internal set; }

        [SqlQueryProperty("name")]
        public override string Name { get; internal set; }

        [SqlQueryProperty("delete_referential_action")]
        public SqlForeignKeyAction DeleteAction { get; internal set; }

        [SqlQueryProperty("is_checked")]
        public bool IsChecked { get; internal set; }

        [SqlQueryProperty("is_enabled")]
        public bool IsEnabled { get; internal set; }

        [SqlQueryProperty("is_system_named")]
        public bool IsSystemNamed { get; internal set; }

        [SqlQueryProperty("is_not_for_replication")]
        public bool NotForReplication { get; internal set; }

        [SqlQueryProperty("update_referential_action")]
        public SqlForeignKeyAction UpdateAction { get; internal set; }

        public ISqlObjectCollection Columns { get { return _foreignKeyColumnList.Value; } }

        public MSSqlForeignKey() : this(null, null) { }

        public MSSqlForeignKey(ISchemaFactory schemaFactory, IDatabase database)
            : base(schemaFactory, database)
        {
            InitLazyObjects();
        }

        private void InitLazyObjects()
        {
            _foreignKeyColumnList = new Lazy<ISqlObjectCollection>(() =>
            {
                return GetChildren<MSSqlForeignKeyColumn>();
            });
        }

        public override ISqlObjectCollection GetChildren<TChild>()
        {
            return base.Factory.GetObjectList<TChild>(this, null, base.Database);
        }

        public override void Refresh()
        {
            base.Refresh();
            base.Factory.ClearObjectList<MSSqlForeignKeyColumn>(base.Database);
            InitLazyObjects();
        }
    }
}
